// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package task

import (
	"context"
	"fmt"

	"github.com/kumose/kmopt/pkg/cluster/ctxt"
	"github.com/kumose/kmopt/pkg/cluster/spec"
	"github.com/kumose/kmopt/pkg/meta"
	"github.com/kumose/kmopt/pkg/utils"
)

// ScaleConfig is used to copy all configurations to the target directory of path
type ScaleConfig struct {
	specManager    *spec.SpecManager
	clusterName    string
	clusterVersion string
	instance       spec.Instance
	base           spec.Topology
	deployUser     string
	paths          meta.DirPaths
}

// Execute implements the Task interface
func (c *ScaleConfig) Execute(ctx context.Context) error {
	// Copy to remote server
	exec, found := ctxt.GetInner(ctx).GetExecutor(c.instance.GetManageHost())
	if !found {
		return ErrNoExecutor
	}

	c.paths.Cache = c.specManager.Path(c.clusterName, spec.TempConfigPath)
	if err := utils.MkdirAll(c.paths.Cache, 0755); err != nil {
		return err
	}

	return c.instance.ScaleConfig(ctx, exec, c.base, c.clusterName, c.clusterVersion, c.deployUser, c.paths)
}

// Rollback implements the Task interface
func (c *ScaleConfig) Rollback(ctx context.Context) error {
	return ErrUnsupportedRollback
}

// String implements the fmt.Stringer interface
func (c *ScaleConfig) String() string {
	return fmt.Sprintf("ScaleConfig: cluster=%s, user=%s, host=%s, service=%s, %s",
		c.clusterName, c.deployUser, c.instance.GetManageHost(), c.instance.ServiceName(), c.paths)
}
